<?php

namespace App\Models\CacheModel\zl4;

use app\common\lib\horoscope\Horoscope;
use App\Models\Api\BaseCache;
use Overtrue\ChineseCalendar\Calendar;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl4HoroscopeGoodTimeTemp extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl4_horoscope_good_time_temp';

    protected $cacheModel = 'horoscope.good_time_report_temp';

    /**
     * 记录 临时 吉日吉时 数据
     * @param array $data
     * @return int|string
     */
    public function SaveData(array $data)
    {
        try
        {
//            $data = [
//                'uid' => $this->user['id'],
//                'hash' => $cacheData['hash'],
//                'rid1' => $cacheData['rid1'],
//                'rid2' => $cacheData['rid2'],
//                'tid' => $cacheData['tid'],
//                'status' => 1,
//                'start_date' => $startTimestamp,
//                'end_date' => $endTimestamp,
//                'day_num' => 0,
//                'unlock_day_num' => $cacheData['unlock_day_num'],
//                'unlock_days' => $cacheData['unlock_days'],
//                'content' => '',
//                'recode_info' => $cacheData['recode_info'],
//                'extend' => [
//                    'unlocked_day_num' => $cacheData['unlocked_day_num'],
//                    'unlocked_days' => $cacheData['unlocked_days'],
//                    'gid' => $cacheData['gid'],
//                    'or_prize' => $cacheData['or_prize'],
//                    'now_prize' => $cacheData['now_prize'],
//                ],
//                'create_time' => $this->request->time(),
//            ];

            $data['unlock_days'] = json_encode($data['unlock_days'], true);
            $data['recode_info'] = json_encode($data['recode_info'], true);
            $data['extend'] = json_encode($data['extend'], true);

            $id = $this->insertGetId($data);
            return $id;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeGoodTimeTemp model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return 0;
        }
    }

    /**
     * 更新报告数据
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, array $data): bool
    {
        try
        {
            $this->where('id', $id)->update($data);
            // 删除缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            Log::write('Zl4HoroscopeGoodTimeTemp model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {   // 获取未删除 的数据
                $data = $this
                    ->where(['id' => ['in', $ids]])
                    ->column('id,uid,hash,rid1,rid2,tid,status,start_date,end_date,unlock_day_num,unlock_days,content,recode_info,extend,create_time,end_time,day_num', 'id');
            } else
            {
                $data = $this->where(['uid' => $type[0]])->order('id desc')->column('id,uid,hash,rid1,rid2,tid,status,start_date,end_date,unlock_day_num,unlock_days,content,recode_info,extend,create_time,end_time,day_num', 'id');
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'rid1', 'rid2', 'tid', 'status', 'start_date', 'end_date', 'unlock_day_num', 'day_num', 'end_time', 'create_time']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }

            if (isset($itemData['unlock_days']))
            {
                $data[$index]['unlock_days'] = $itemData['unlock_days'] ? json_decode($itemData['unlock_days'], true) : [];
            }

            if (isset($itemData['content']))
            {
                $data[$index]['content'] = $itemData['content'] ? json_decode($itemData['content'], true) : [];
            }

            if (isset($itemData['recode_info']))
            {
                $data[$index]['recode_info'] = $itemData['recode_info'] ? json_decode($itemData['recode_info'], true) : [];
            }
        }

        return $data;
    }

    /**
     * 重组 吉日吉时信息
     * @param string $jiri
     * @param array $jishi
     * @return array
     */
    public static function resertGoodTimeData(string $tagName, string $jiri, array $jishi)
    {
        [$y, $m, $d] = explode('-', $jiri);

        $nongliData = (new Calendar())->solar($y, $m, $d);
        $nongli = $nongliData['lunar_month_chinese'] . $nongliData['lunar_day_chinese'];

        $weekDayConfig = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        $w = date('w', strtotime($jiri));

        $res = Horoscope::getInstance()->getLiuri(strtotime($jiri), 1);
        $liunian = isset($res[$jiri], $res[$jiri]['liunian']) ? $res[$jiri]['liunian'] : [];

        $jishiConfig = [
            '子' => ['time_des' => '子时', 'color' => '#5F7CEE', 'times' => '23-1点'],
            '丑' => ['time_des' => '丑时', 'color' => '#EC8337', 'times' => '1-3点'],
            '寅' => ['time_des' => '寅时', 'color' => '#EC8337', 'times' => '3-5点'],
            '卯' => ['time_des' => '卯时', 'color' => '#EC8337', 'times' => '5-7点'],
            '辰' => ['time_des' => '辰时', 'color' => '#EC8337', 'times' => '7-9点'],
            '巳' => ['time_des' => '巳时', 'color' => '#ECAB23', 'times' => '9-11点'],
            '午' => ['time_des' => '午时', 'color' => '#ECAB23', 'times' => '11-13点'],
            '未' => ['time_des' => '未时', 'color' => '#ECAB23', 'times' => '13-15点'],
            '申' => ['time_des' => '申时', 'color' => '#ECAB23', 'times' => '15-17点'],
            '酉' => ['time_des' => '酉时', 'color' => '#5F7CEE', 'times' => '17-19点'],
            '戌' => ['time_des' => '戌时', 'color' => '#5F7CEE', 'times' => '19-21点'],
            '亥' => ['time_des' => '亥时', 'color' => '#5F7CEE', 'times' => '21-23点'],
        ];
        $jishiTime = [];
        foreach ($jishi as $shichen)
        {
            if (isset($jishiConfig[$shichen]))
            {
                $jishiTime[] = $jishiConfig[$shichen];
            }
        }

        return [
            'date' => $jiri,
            'date_des' => '农历' . $nongli,
            'week' => $weekDayConfig[$w],
            'date_des2' => '农历' . implode('', $liunian) . '年 ' . $nongli,
            'good_times' => $jishiTime,
            'alert_title' => $tagName . '的最佳推荐吉时：',
        ];
    }
}
